package com.nf.health.app.homepage.activity;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.nf.health.app.Constants;
import com.nf.health.app.R;
import com.nf.health.app.activity.global.BaseActivity;
import com.nf.health.app.adapter.EvaluationQuestionAdapter;
import com.nf.health.app.models.EvaluationQuestion;
import com.nf.health.app.models.Result;
import com.nf.health.app.utils.ScreentUtils;
import com.nf.health.app.utils.ViewUtil;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 健康自测——答题页
 *
 * @author lgs
 */
public class EvaluationActivity extends BaseActivity implements OnClickListener {


    StringBuilder sb;

    protected static final String TAG = EvaluationActivity.class
            .getSimpleName();
    private TextView tv_question_title;
    Dialog rdialog;
    private ImageView titlebar_back_view;
    private ArrayList<Map<Integer, Boolean>> isChecedList;
    private String evalFlag;
    private ListView listview;
    private ImageView iv_prepage;
    private ImageView iv_nextpage;

    private String title;

    // private TextView tv_percentage;
    // private ProgressBar progress_bar;
    private List<EvaluationQuestion> questions;
    private EvaluationQuestionAdapter adapter;
    private TextView tv_evaluation_num;// 答题提示框
    private static final String SINGLE_CHOICE = "1";
    private static final String MUTI_CHOICE = "2";
    /**
     * 当前题目的索引值
     */
    private int currentQuestionIndex = 0;
    private Handler handler = new Handler();
    private View ll_content;

    private static final String ASSESS_CALL_BACK_KEY = "assess_call_back_key";
    private static final String ASSESS_RESULT_KEY = "assess_result";
    private boolean isCallBackResult;// 是否需要把结果回传给调用它的Activity  采用startActivityForResult形式
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setTitleBar(R.layout.titlebar_base);
        setContent(R.layout.activity_evaluation);
        title = getIntent().getStringExtra("title");
        ViewUtil.setText(this, R.id.titlebar_title_tv, title);
        tv_question_title = (TextView) findViewById(R.id.tv_question_title);
        titlebar_back_view = (ImageView) findViewById(R.id.titlebar_back_view);
        iv_prepage = (ImageView) findViewById(R.id.iv_prepage);
        iv_nextpage = (ImageView) findViewById(R.id.iv_nextpage);
        listview = (ListView) findViewById(R.id.listview);
        tv_evaluation_num = (TextView) findViewById(R.id.tv_evaluation_numId);
        ll_content = ViewUtil.getView(this, R.id.ll_content);
        iv_nextpage.setImageResource(R.drawable.bt_next_s);
        initData();
        initListener();
//        HashMap<String, String> map = new HashMap<String, String>();
//        for(int i=1;i<=33;i++){
//            map.put(""+i,"2");
//        }
//        provider.requestEvaluationCalculate(map, evalFlag, "calculate");
    }

    private void initData() {
        evalFlag = getIntent().getStringExtra("evalFlag");
        isCallBackResult = getIntent().getBooleanExtra(ASSESS_CALL_BACK_KEY,false);
        provider.requestEvaluationQueslist(evalFlag, "requestEvaluationQueslist");
    }

    private void initListener() {
        titlebar_back_view.setOnClickListener(this);
        iv_prepage.setOnClickListener(this);
        iv_nextpage.setOnClickListener(this);

        listview.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View item,
                                    int position, long arg3) {
                String type = questions.get(currentQuestionIndex).getType();
                // 标记当前问题是否已经作答
                if (SINGLE_CHOICE.equals(type)) {
//					questions.get(currentQuestionIndex).setChecked(true);
                    // 选中某个答案，需要重新其他选项
                    for (int i = 0; i < questions.get(currentQuestionIndex)
                            .getAnswer().size(); i++) {
                        if (i == position) {
                            isChecedList.get(currentQuestionIndex).put(i, true);
                        } else {
                            isChecedList.get(currentQuestionIndex).put(i, false);
                        }
                    }
                    adapter.notifyDataSetChanged();
                    if (currentQuestionIndex == questions.size() - 1) {
                        //						adapter.notifyDataSetChanged();
                    } else {
                        handler.postDelayed(new Runnable() {

                            @Override
                            public void run() {
                                currentQuestionIndex++;
                                //延迟更新当前view
                                refreshView();
                            }
                        }, 100);
                    }
                } else if (MUTI_CHOICE.equals(type)) {
                    if (isChecedList.get(currentQuestionIndex).get(position)) {
                        isChecedList.get(currentQuestionIndex).put(position, false);
                    } else {
                        isChecedList.get(currentQuestionIndex).put(position, true);
                    }
                    if (currentQuestionIndex == questions.size() - 1) {
                        // TODO 修改按钮为 完成
                        iv_nextpage.setImageResource(R.drawable.bt_finish);
                    } /*else if (questions.get(currentQuestionIndex).isChecked()) {
                        iv_nextpage.setImageResource(R.drawable.bt_next_s);
					}*/ else {
                        Map<Integer, Boolean> map = isChecedList.get(currentQuestionIndex);
                        if (map.containsValue(true)) {
                            iv_nextpage.setImageResource(R.drawable.bt_next_s);
                        } else {
                            iv_nextpage.setImageResource(R.drawable.bt_next);
                        }
                    }
                    adapter.notifyDataSetChanged();
                }
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.titlebar_back_view:
                finish();
                break;
            case R.id.iv_prepage:
                if (currentQuestionIndex == 0) {
                    showToast("已经是第1道题了");
                    return;
                }
                currentQuestionIndex--;
                refreshView();
                break;
            case R.id.iv_nextpage:
                if (questions == null) {
                    return;
                }
//			if (!questions.get(currentQuestionIndex).isChecked()) {
//				showToast("这道题目还未作答");
//				return;
//			}
                Map<Integer, Boolean> map = isChecedList.get(currentQuestionIndex);
                if (!map.containsValue(true)) {
                    showToast("这道题目还未作答");
                    return;
                }

                if (currentQuestionIndex == questions.size() - 1) {
                    // TODO 执行完成方法
                    commitAnswer();
                    return;
                }

                currentQuestionIndex++;

                refreshView();

                break;
            default:
                break;
        }
    }

    private void commitAnswer() {
        HashMap<String, String> map = new HashMap<String, String>();
        for (int j = 0; j < questions.size(); j++) {
            sb = new StringBuilder();
            for (int i = 0; i < questions.get(j).getAnswer().size(); i++) {
                if (isChecedList.get(j).get(i)) {
                    // 因为问题答案的key是从1开始的。所以索引需加1
                    sb.append(String.valueOf(i + 1));
//					sb.append(",");
                }
            }
            try {
                map.put(questions.get(j).getQnumber(), sb.substring(0, sb.toString().length()));// - 1
            } catch (Exception e1) {
                e1.printStackTrace();
            }
        }

        provider.requestEvaluationCalculate(map, evalFlag, "calculate");
    }

    @SuppressWarnings("unchecked")
    @Override
    public void handleActionSuccess(String actionName, Object object) {
        super.handleActionSuccess(actionName, object);
        if ("requestEvaluationQueslist".equals(actionName)) {

            questions = (List<EvaluationQuestion>) object;
            if (questions != null) {
                // TODO
                for (EvaluationQuestion item : questions) {
                    item.convert();
                }

                isChecedList = new ArrayList<Map<Integer, Boolean>>();
                for (int i = 0; i < questions.size(); i++) {
                    HashMap<Integer, Boolean> answer = new HashMap<Integer, Boolean>();
                    int answerCount = Integer.parseInt(questions.get(i).getAnswercount());
                    Log.i(TAG, "" + answerCount);
                    for (int j = 0; j < answerCount; j++) {
                        answer.put(j, false);
                    }
                    isChecedList.add(answer);
                }

                refreshView();
                ll_content.setVisibility(View.VISIBLE);
            }
        } else if ("calculate".equals(actionName)) {
            if(!isCallBackResult) {
                Result result = (Result) object;
                showToast("测评成功");
                if("chinesemedicine".equals(evalFlag) || "chinesemedicine1".equals(evalFlag)){
                    Intent intent = new Intent(EvaluationActivity.this, NewCheckResultActivity.class);
                    intent.putExtra(Constants.BEAN_KEY,result);
                    startActivity(intent);
                }else{
                    Intent intent = new Intent(EvaluationActivity.this, EndCheckActivity.class);
                    intent.putExtra("score", result.getScore());
                    intent.putExtra("result", result.getResult());
                    intent.putExtra("url", result.getUrl());
                    intent.putExtra("list", (Serializable) result.getList());
                    intent.putExtra("count", questions.size());
                    startActivity(intent);
                }
                provider.requestAddScore("1", "addScore");//添加积分
                finish();
            }else{
                Result result = (Result) object;
                Intent intent = new Intent();
                intent.putExtra(ASSESS_RESULT_KEY,result.getResult());
                setResult(RESULT_OK,intent);
                finish();
            }
        }
    }

    /**
     * 刷新页面，显示另外一题
     */
    private void refreshView() {
        if (currentQuestionIndex == 0) {
            iv_prepage.setVisibility(View.GONE);
        } else {
            iv_prepage.setVisibility(View.VISIBLE);
        }
        if (currentQuestionIndex == questions.size() - 1) {
            // TODO 修改按钮为 完成
            iv_nextpage.setImageResource(R.drawable.bt_finish);
        } else {
            if (currentQuestionIndex == questions.size()) {
            } else {
                Map<Integer, Boolean> map = isChecedList.get(currentQuestionIndex);
                if (map.containsValue(true)) {
                    iv_nextpage.setImageResource(R.drawable.bt_next_s);
                } else {
                    iv_nextpage.setImageResource(R.drawable.bt_next);
                }
            }
        }

        tv_evaluation_num.setText("本测试一共" + questions.size() + "道题，还剩" + (questions.size() - currentQuestionIndex - 1) + "道题");
        tv_question_title.setText((currentQuestionIndex + 1) + ". " + questions.get(currentQuestionIndex).getTitle());
        adapter = new EvaluationQuestionAdapter(this, questions.get(currentQuestionIndex), isChecedList.get(currentQuestionIndex));
        listview.setAdapter(adapter);
        ScreentUtils.setListViewHeightBasedOnChildren(listview);
    }

}
